import { Injectable, OnModuleInit } from '@nestjs/common';
import { drizzle } from 'drizzle-orm/mysql2';
import * as dotenv from 'dotenv';
import * as mysql from 'mysql2/promise';

dotenv.config();

@Injectable()
export class DrizzleService implements OnModuleInit {
  public db;

  async onModuleInit() {
    try {
      // 使用 mysql2 的正确方式创建连接池
      const pool = mysql.createPool({
        host: process.env.DB_HOST,
        port: Number(process.env.DB_PORT),
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME,
        // 添加额外配置以提高稳定性
        waitForConnections: true,
        connectionLimit: 10,
        queueLimit: 0,
      });

      // 测试连接
      await pool.getConnection();
      this.db = drizzle(pool,{
        logger: true,
      });
    } catch (error) {
      console.error('数据库连接错误:', error);
      throw error;
    }
  }
} 